package com.hontech.desktoppastacooker.utils


private val HEX_LIST = arrayOf(
    '0', '1', '2', '3',
    '4', '5', '6', '7',
    '8', '9', 'a', 'b',
    'c', 'd', 'e', 'f'
)

fun Byte.toUint8() = this.toInt() and 0xFF

fun ByteArray.xorSum(index: Int, len: Int): Int {
    var s = 0
    for (i in index until (index + len)) {
        val value = this[i].toUint8()
        s = s xor value
    }
    return s
}

fun Int.toHex4(): String {
    val value = this and 0xFFFF
    val l0 = (value shr 12) and 0x0F
    val l1 = (value shr 8) and 0x0F
    val l2 = (value shr 4) and 0x0F
    val l3 = value and 0x0F
    return String(charArrayOf(
        HEX_LIST[l0],
        HEX_LIST[l1],
        HEX_LIST[l2],
        HEX_LIST[l3]
    ))
}

fun Int.isSetbit(offset: Int) = (this and  (0x01 shl offset)) != 0

fun Byte.toHex(): String {
    val value = this.toInt()
    val h = value shr 4
    val l = value and 0x0F
    return String(charArrayOf(HEX_LIST[h], HEX_LIST[l]))
}

fun ByteArray.toHex(index: Int = 0, len: Int = size - index): String {
    val buf = CharArray(len * 3)
    for (i in 0 until len) {
        val value = this[i + index].toUint8()
        val h = value shr 4
        val l = value and 0x0F
        buf[i * 3 + 0] = HEX_LIST[h]
        buf[i * 3 + 1] = HEX_LIST[l]
        buf[i * 3 + 2] = ' '
    }
    return String(buf)
}

fun ByteArray.toEpcHex(index: Int = 0, len: Int = size - index): String {
    val buf = CharArray(len * 2)
    for (i in 0 until len) {
        val value = this[i + index].toUint8()
        val h = value shr 4
        val l = value and 0x0F
        buf[i * 2 + 0] = HEX_LIST[h]
        buf[i * 2 + 1] = HEX_LIST[l]
    }
    return String(buf)
}

fun ByteArray.toMacHex(index: Int = 0, len: Int = size - index): String {
    val buf = CharArray(len * 3)
    for (i in 0 until len) {
        val value = this[i + index].toInt()
        val h = value shr 4
        val l = value and 0x0F
        buf[i * 3 + 0] = HEX_LIST[h]
        buf[i * 3 + 1] = HEX_LIST[l]
        buf[i * 3 + 2] = ' '
    }
    return String(buf)
}






